package com.service.abolishing.config;

import com.service.config.dto.MailBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName: MailUtil
 * @Description:
 * @Author guochuang
 * @Date 2021/10/25
 * @Version 1.0
 */
@Component
public class MailUtil {
    @Value("${Spring.mail.username}")
    private String MAIL_SENDER; //邮件发送者
    @Value("${Spring.mail.password}")
    private String password; //邮件发送者
    @Value("${Spring.mail.host}")
    private String host; //邮件发送者
    @Value("${Spring.mail.port}")
    private String port; //邮件发送者
    private String TEMP; //邮件发送者
    @Autowired
    private JavaMailSender javaMailSender;

    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**
     * 发送文本邮件
     *
     * @param mailBean
     */
    public  void sendSimpleMail(MailBean mailBean) {
        try {
            SimpleMailMessage mailMessage= new SimpleMailMessage();
            mailMessage.setFrom(MAIL_SENDER);
            mailMessage.setTo(mailBean.getRecipient());
            mailMessage.setSubject(mailBean.getSubject());
            mailMessage.setText(mailBean.getContent());
            //mailMessage.copyTo(copyTo);

            javaMailSender.send(mailMessage);
        } catch (Exception e) {
            logger.error("email send failure", e.getMessage());
        }
    }

    /**
     * 发送邮件内容包含表格
     * @param mailBean
     */
    public void sendHTMLMail(MailBean mailBean) {
        MimeMessage mimeMailMessage = null;
        try {
//            mimeMailMessage = javaMailSender.createMimeMessage();
//            //true 表示需要创建一个multipart message
//            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
//            mimeMessageHelper.setFrom(MAIL_SENDER);
//            mimeMessageHelper.setTo(mailBean.getRecipient());
//            mimeMessageHelper.setSubject(mailBean.getSubject());
//            //邮件抄送
//            //mimeMessageHelper.addCc("抄送人");
//            mimeMessageHelper.setText(mailBean.getContent(), true);
//            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("邮件发送失败： "+mailBean.getRecipient()+"    时间为："+new Date());
        }
    }

    /**
     * 发送邮件内容包含表格
     * @param mailBean
     */
    public void sendHTML(MailBean mailBean) {
        try {
            //SendMail.sendHtml(port,host,MAIL_SENDER,password,mailBean);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    private Transport getTransport(Session session) throws NoSuchProviderException {
        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport( "smtp");
        return transport;
    }

    private Session getSession(Properties props) {
        return Session.getInstance(props);
    }

    private Properties getProps() {
        // 1. 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.smtp.host", host);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
        return props;
    }

    /**
     * 发送邮件内容包含表格
     * @param mailBeans
     */
    public void sendHTMList(List<MailBean> mailBeans) {
        try {
            Properties props = getProps();
            // 2. 根据配置创建会话对象, 用于和邮件服务器交互
            Session session = getSession(props);
            List<MimeMessage> mimeMessageList = new ArrayList<>();
            for (int i = 0 ; i < mailBeans.size() ; i++) {
                MimeMessage mimeMessage = SendMail.createMimeMessage(session, MAIL_SENDER.concat("@cloudcampusapps.top"), mailBeans.get(i));
                mimeMessageList.add(mimeMessage);
            }
            // 4. 根据 Session 获取邮件传输对象
            Transport transport = getTransport(session);
            // 5. 使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
            transport.connect(host,MAIL_SENDER, password);
            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            mimeMessageList.stream().forEach(mimeMessage -> {
                try {
                    transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            });
            transport.close();
        } catch (Exception e) {
            logger.error(e.getMessage());
            logger.error("邮件发送失败时间为："+new Date());
        }
    }
    /**
     * 附件格式发送
     * @param mailBean
     */
    public void sendAttachmentMail(MailBean mailBean) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            //true 表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailBean.getRecipient());
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent());
            //文件路径 目前写死在代码中，之后可以当参数传过来，或者在MailBean中添加属性absolutePath
            String absolutePath = "D:\\Program Files\\test.jpg";
            FileSystemResource file = new FileSystemResource(new File(absolutePath));
            //FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/image/email.png"));
            String fileName = absolutePath.substring(absolutePath.lastIndexOf(File.separator));
            //添加附件,第一个参数表示添加到 Email 中附件的名称，第二个参数是图片资源
            mimeMessageHelper.addAttachment(fileName, file);
            //多个附件
            //mimeMessageHelper.addAttachment(fileName1, file1);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            logger.error("邮件发送失败", e.getMessage());
        }
    }

    public void sendAttachmentMail(MailBean mailBean, MultipartFile file) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            //true 表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            mimeMessageHelper.setTo(mailBean.getRecipient());
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent());
            String originalFilename = file.getOriginalFilename();
            //获取后缀
            File localFile = new File(TEMP + originalFilename);
            file.transferTo(localFile);
            //保存路径
            //springboot 默认情况下只能加载 resource文件夹下静态资源文件
            //添加附件,第一个参数表示添加到 Email 中附件的名称，第二个参数是图片资源
            mimeMessageHelper.addAttachment(originalFilename, localFile);
            //多个附件
            //mimeMessageHelper.addAttachment(fileName1, file1);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            logger.error("邮件发送失败", e.getMessage());
        }
    }

    /**
     * post形式发送
     * MaailBean中包含文件路径
     * @param mailBean
     */
    public void sendAttachmentMailAndPost(MailBean mailBean) {
        MimeMessage mimeMailMessage = null;
        try {
            mimeMailMessage = javaMailSender.createMimeMessage();
            //true 表示需要创建一个multipart message
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            mimeMessageHelper.setFrom(MAIL_SENDER);
            // 多个收件人 以逗号隔开
            InternetAddress[] internetAddressTo = InternetAddress.parse(mailBean.getRecipient().replace(";",","));
            if (internetAddressTo.length >0){
                mimeMailMessage.setRecipients(Message.RecipientType.TO,internetAddressTo);
                //mimeMessageHelper.setTo(mailBean.getRecipient());
                mimeMessageHelper.setSubject("网络状态报告");
                mimeMessageHelper.setText("网络状态报告");
                // String originalFilename = file.getOriginalFilename();
                //获取后缀 多附件
                String[] split = mailBean.getEnclosurePath().split(",");
                for (int i = 0 ; i < split.length ; i++){
                    File localFile = new File(split[i]);
                    //springboot 默认情况下只能加载 resource文件夹下静态资源文件
                    //添加附件,第一个参数表示添加到 Email 中附件的名称，第二个参数是图片资源
                    mimeMessageHelper.addAttachment(localFile.getName(), localFile);
                }
                //mimeMessageHelper.addAttachment(fileName1, file1);
                mimeMailMessage.saveChanges();
                javaMailSender.send(mimeMailMessage);
            }
        } catch (Exception e) {
            logger.error("邮件发送失败", e.getMessage());
        }
    }
    /**
     * 创建一封只包含文本的简单邮件
     *
     * @param session 和服务器交互的会话
     * @param sendMail 发件人邮箱
     * @param mailBean 收件人邮箱
     * @return
     * @throws Exception
     */
    public  MimeMessage createMimeMessage(Session session, String sendMail, MailBean mailBean) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
        message.setFrom(new InternetAddress(sendMail, mailBean.getFromToName(), "UTF-8"));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(mailBean.getRecipient(), mailBean.getRecipientName(), "UTF-8"));

        // 4. Subject: 邮件主题（标题有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改标题）
        message.setSubject(mailBean.getSubject(), "UTF-8");

        // 5. Content: 邮件正文（可以使用html标签）（内容有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改发送内容）
        message.setContent(mailBean.getContent(), "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

}
